/**
 * 创作日历组件
 * 展示用户的创作活动热力图
 */
import React, { useEffect, useState } from 'react';
import { Card, Select, Tooltip, Space, Typography, Row, Col, Statistic } from 'antd';
import { CalendarOutlined, FireOutlined } from '@ant-design/icons';
import { useStatisticsStore } from '@/stores/statistics.store';
import type { CalendarData } from '@/types/statistics';
import './style.css';

const { Title, Text } = Typography;

interface CreationCalendarProps {
  className?: string;
}

export const CreationCalendar: React.FC<CreationCalendarProps> = ({ className }) => {
  const { calendarData, loading, loadCalendarData } = useStatisticsStore();
  const [selectedYear, setSelectedYear] = useState(new Date().getFullYear());
  const [selectedMonth, setSelectedMonth] = useState<number | undefined>(
    new Date().getMonth() + 1
  );

  useEffect(() => {
    loadCalendarData(selectedYear, selectedMonth);
  }, [selectedYear, selectedMonth, loadCalendarData]);

  // 生成年份选项
  const yearOptions = Array.from({ length: 5 }, (_, i) => {
    const year = new Date().getFullYear() - i;
    return { label: `${year}年`, value: year };
  });

  // 生成月份选项
  const monthOptions = [
    { label: '全年', value: undefined },
    ...Array.from({ length: 12 }, (_, i) => ({
      label: `${i + 1}月`,
      value: i + 1,
    })),
  ];

  // 获取日历数据统计
  const calendarStats = React.useMemo(() => {
    const dates = Object.keys(calendarData);
    const totalDays = dates.length;
    const totalWords = dates.reduce(
      (sum, date) => sum + (calendarData[date]?.wordCount || 0),
      0
    );
    const maxStreak = calculateMaxStreak(calendarData);

    return { totalDays, totalWords, maxStreak };
  }, [calendarData]);

  // 计算最大连续天数
  function calculateMaxStreak(data: CalendarData): number {
    const sortedDates = Object.keys(data).sort();
    if (sortedDates.length === 0) return 0;

    let maxStreak = 1;
    let currentStreak = 1;

    for (let i = 1; i < sortedDates.length; i++) {
      const prevDate = new Date(sortedDates[i - 1]);
      const currDate = new Date(sortedDates[i]);
      const dayDiff =
        (currDate.getTime() - prevDate.getTime()) / (1000 * 60 * 60 * 24);

      if (dayDiff === 1) {
        currentStreak++;
        maxStreak = Math.max(maxStreak, currentStreak);
      } else {
        currentStreak = 1;
      }
    }

    return maxStreak;
  }

  // 获取热度等级
  const getHeatLevel = (wordCount: number): number => {
    if (wordCount === 0) return 0;
    if (wordCount < 500) return 1;
    if (wordCount < 1500) return 2;
    if (wordCount < 3000) return 3;
    return 4;
  };

  // 渲染日历热力图
  const renderCalendarHeatmap = () => {
    const startDate = selectedMonth
      ? new Date(selectedYear, selectedMonth - 1, 1)
      : new Date(selectedYear, 0, 1);

    const endDate = selectedMonth
      ? new Date(selectedYear, selectedMonth, 0)
      : new Date(selectedYear, 11, 31);

    const weeks: Date[][] = [];
    let currentWeek: Date[] = [];
    const current = new Date(startDate);

    // 补充开始日期前的空白
    const startDay = current.getDay();
    for (let i = 0; i < startDay; i++) {
      currentWeek.push(new Date(0)); // 空日期
    }

    // 填充日期
    while (current <= endDate) {
      currentWeek.push(new Date(current));

      if (currentWeek.length === 7) {
        weeks.push(currentWeek);
        currentWeek = [];
      }

      current.setDate(current.getDate() + 1);
    }

    // 补充结束日期后的空白
    if (currentWeek.length > 0) {
      while (currentWeek.length < 7) {
        currentWeek.push(new Date(0));
      }
      weeks.push(currentWeek);
    }

    return (
      <div className="calendar-heatmap">
        <div className="calendar-weekdays">
          {['日', '一', '二', '三', '四', '五', '六'].map((day) => (
            <div key={day} className="weekday-label">
              {day}
            </div>
          ))}
        </div>

        {weeks.map((week, weekIndex) => (
          <div key={weekIndex} className="calendar-week">
            {week.map((date, dayIndex) => {
              if (date.getTime() === 0) {
                return <div key={dayIndex} className="calendar-day empty" />;
              }

              const dateStr = date.toISOString().split('T')[0];
              const dayData = calendarData[dateStr];
              const heatLevel = dayData ? getHeatLevel(dayData.wordCount) : 0;

              return (
                <Tooltip
                  key={dayIndex}
                  title={
                    dayData ? (
                      <div>
                        <div>{dateStr}</div>
                        <div>创作: {dayData.wordCount} 字</div>
                        <div>文章: {dayData.articleCount} 篇</div>
                        {dayData.qualityScore && (
                          <div>质量: {dayData.qualityScore} 分</div>
                        )}
                      </div>
                    ) : (
                      <div>
                        <div>{dateStr}</div>
                        <div>无创作记录</div>
                      </div>
                    )
                  }
                >
                  <div className={`calendar-day heat-level-${heatLevel}`}>
                    <span className="day-number">{date.getDate()}</span>
                  </div>
                </Tooltip>
              );
            })}
          </div>
        ))}
      </div>
    );
  };

  return (
    <div className={`creation-calendar ${className || ''}`}>
      <Card
        title={
          <Space>
            <CalendarOutlined />
            <span>创作日历</span>
          </Space>
        }
        extra={
          <Space>
            <Select
              value={selectedYear}
              onChange={setSelectedYear}
              options={yearOptions}
              style={{ width: 100 }}
            />
            <Select
              value={selectedMonth}
              onChange={setSelectedMonth}
              options={monthOptions}
              style={{ width: 100 }}
            />
          </Space>
        }
        loading={loading}
      >
        {/* 统计信息 */}
        <Row gutter={16} style={{ marginBottom: 24 }}>
          <Col span={8}>
            <Statistic
              title="创作天数"
              value={calendarStats.totalDays}
              suffix="天"
              prefix={<CalendarOutlined />}
            />
          </Col>
          <Col span={8}>
            <Statistic
              title="总字数"
              value={calendarStats.totalWords}
              suffix="字"
            />
          </Col>
          <Col span={8}>
            <Statistic
              title="最长连续"
              value={calendarStats.maxStreak}
              suffix="天"
              prefix={<FireOutlined />}
            />
          </Col>
        </Row>

        {/* 日历热力图 */}
        {renderCalendarHeatmap()}

        {/* 热度等级说明 */}
        <div className="heat-legend">
          <Text type="secondary">少</Text>
          <div className="legend-squares">
            <div className="legend-square heat-level-0" />
            <div className="legend-square heat-level-1" />
            <div className="legend-square heat-level-2" />
            <div className="legend-square heat-level-3" />
            <div className="legend-square heat-level-4" />
          </div>
          <Text type="secondary">多</Text>
        </div>
      </Card>
    </div>
  );
};

export default CreationCalendar;
